package com.topInterview;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @Author: huangzhigao
 * @Date: 2022/2/20 15:49
 */
public class Leecode56_mergeInterval {
    public int[][] merge(int[][] intervals) {
        Range[] ranges = new Range[intervals.length];
        for (int i = 0; i < intervals.length; i++) {
            ranges[i] = new Range(intervals[i][0], intervals[i][1]);
        }

        Arrays.sort(ranges, new MyComparotor());
        if (ranges.length < 1) {
            return new int[0][0];
        }

        int start = ranges[0].start;
        int end = ranges[0].end;

        List<Range> list = new ArrayList<>();

        for (int i = 1; i < ranges.length; i++) {
            if (ranges[i].start > end) {
                list.add(new Range(start, end));
                start = ranges[i].start;
                end = ranges[i].end;
            } else {
                end = Math.max(end, ranges[i].end);
            }
        }
        list.add(new Range(start, end));

        int[][] res = new int[list.size()][2];
        for (int i = 0; i < list.size(); i++) {
            res[i][0] = list.get(i).start;
            res[i][1] = list.get(i).end;
        }
        return res;
    }


    public class MyComparotor implements Comparator<Range> {

        @Override
        public int compare(Range o1, Range o2) {
            return o1.start - o2.start;
        }
    }


    public class Range {
        private int start;
        private int end;

        public Range(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }
}
